package com.tencent.common.exception;

import com.google.common.collect.ImmutableMap;
import com.tencent.common.pojo.Result;
import com.tencent.common.pojo.StatusCode;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionCatch {

    private static ImmutableMap<Class<? extends Throwable>, Result> EXCEPTION;

    private static ImmutableMap.Builder<Class<? extends Throwable>, Result> builder = ImmutableMap.builder();

    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public Result customException(CustomerException e){
        return e.getResult();
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception e){
        e.printStackTrace();
        //记录日志
        if(EXCEPTION == null)
            EXCEPTION = builder.build(); //构建初始化
        final Result result = EXCEPTION.get(e.getClass());
        if (result != null) {
            //如果匹配了异常  直接返回对应异常提示
            return result;
        } else {
            // 代表异常没有，返回统一异常码
            return new Result(99999,"出现未知异常",false);
        }
    }


    static{
        //在这里加入一些基础的异常类型判断
        builder.put(HttpMessageNotReadableException.class,new Result(StatusCode.ERROR,"非法参数",false));
        builder.put(NullPointerException.class,new Result(StatusCode.ERROR,"出现空对象异常",false));
        builder.put(IndexOutOfBoundsException.class,new Result(StatusCode.ERROR,"下角标越界异常",false));
        //自己填充的
        builder.put(ArithmeticException.class,new Result(StatusCode.ERROR,"除数不能为0",false));
    }


}
